package com.duan.laugh.common.security.exception;

import com.duan.laugh.common.core.util.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 统一资源权限不足异常格式
 *
 * @author duanjw
 */
@Slf4j
@UtilityClass
public class HttpUtil {

    public void write(HttpServletRequest request, HttpServletResponse response, String message) {
        Map map = new HashMap(3);
        map.put("code", R.FAIL);
        map.put("msg", message);
        map.put("data", null);
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getOutputStream(), map);
        } catch (Exception e) {
            log.error("返回资源权限不足出现异常", e);
        }
    }
}
